"""
对话管理服务
负责会话和消息的管理
"""

from typing import List, Optional, Dict, Any
from sqlalchemy.orm import Session
from sqlalchemy import and_, desc
from datetime import datetime

from app.models.conversation import Conversation, Message
from app.models.user import User
from app.services.base_service import BaseService
from app.schemas.conversation import ConversationCreate, ConversationUpdate, MessageCreate
from app.core.config import settings


class ConversationService(BaseService[Conversation, ConversationCreate, ConversationUpdate]):
    """对话服务"""
    
    def __init__(self):
        super().__init__(Conversation)
    
    def get_user_conversations(
        self, 
        db: Session, 
        user_id: int, 
        skip: int = 0, 
        limit: int = 20
    ) -> List[Conversation]:
        """获取用户的对话列表"""
        return db.query(Conversation).filter(
            and_(
                Conversation.user_id == user_id,
                Conversation.is_active == True
            )
        ).order_by(desc(Conversation.updated_at)).offset(skip).limit(limit).all()
    
    def get_conversation_with_messages(
        self, 
        db: Session, 
        conversation_id: int, 
        user_id: int
    ) -> Optional[Conversation]:
        """获取对话及其消息"""
        return db.query(Conversation).filter(
            and_(
                Conversation.id == conversation_id,
                Conversation.user_id == user_id,
                Conversation.is_active == True
            )
        ).first()
    
    def create_conversation(
        self, 
        db: Session, 
        user_id: int,
        title: Optional[str] = None,
        model_config_id: Optional[int] = None,
        knowledge_base_id: Optional[int] = None,
        prompt_template_id: Optional[int] = None
    ) -> Conversation:
        """创建新对话"""
        conversation = Conversation(
            user_id=user_id,
            title=title or f"新对话 {datetime.now().strftime('%Y-%m-%d %H:%M')}",
            model_config_id=model_config_id,
            knowledge_base_id=knowledge_base_id,
            prompt_template_id=prompt_template_id
        )
        db.add(conversation)
        db.commit()
        db.refresh(conversation)
        return conversation
    
    def add_message(
        self, 
        db: Session, 
        conversation_id: int, 
        role: str, 
        content: str,
        metadata: Optional[Dict[str, Any]] = None,
        token_count: Optional[int] = None
    ) -> Message:
        """添加消息到对话"""
        message = Message(
            conversation_id=conversation_id,
            role=role,
            content=content,
            metadata=metadata,
            token_count=token_count
        )
        db.add(message)
        
        # 更新对话的消息计数和更新时间
        conversation = db.query(Conversation).filter(Conversation.id == conversation_id).first()
        if conversation:
            conversation.message_count += 1
            conversation.updated_at = datetime.utcnow()
        
        db.commit()
        db.refresh(message)
        return message
    
    def get_conversation_messages(
        self, 
        db: Session, 
        conversation_id: int, 
        limit: Optional[int] = None
    ) -> List[Message]:
        """获取对话的消息列表"""
        query = db.query(Message).filter(Message.conversation_id == conversation_id)
        query = query.order_by(Message.created_at)  # 先排序
        if limit:
            query = query.limit(limit)  # 再限制数量
        return query.all()
    
    def check_conversation_length(self, conversation: Conversation) -> Dict[str, Any]:
        """检查对话长度"""
        if conversation.message_count >= settings.max_conversation_length:
            return {
                "exceeded": True,
                "current_count": conversation.message_count,
                "max_count": settings.max_conversation_length,
                "message": f"当前对话已超过{settings.max_conversation_length}轮，建议创建新对话"
            }
        return {
            "exceeded": False,
            "current_count": conversation.message_count,
            "max_count": settings.max_conversation_length
        }
    
    def archive_conversation(self, db: Session, conversation_id: int, user_id: int) -> bool:
        """归档对话"""
        conversation = db.query(Conversation).filter(
            and_(
                Conversation.id == conversation_id,
                Conversation.user_id == user_id
            )
        ).first()
        
        if conversation:
            conversation.is_active = False
            db.commit()
            return True
        return False
    
    def delete_conversation(self, db: Session, conversation_id: int, user_id: int) -> bool:
        """删除对话"""
        conversation = db.query(Conversation).filter(
            and_(
                Conversation.id == conversation_id,
                Conversation.user_id == user_id
            )
        ).first()
        
        if conversation:
            db.delete(conversation)
            db.commit()
            return True
        return False
    
    def update_conversation_title(
        self, 
        db: Session, 
        conversation_id: int, 
        user_id: int, 
        title: str
    ) -> bool:
        """更新对话标题"""
        conversation = db.query(Conversation).filter(
            and_(
                Conversation.id == conversation_id,
                Conversation.user_id == user_id
            )
        ).first()
        
        if conversation:
            conversation.title = title
            db.commit()
            return True
        return False
